import axios from 'axios';
import md5 from 'js-md5';
import qs from 'qs';
import {
    Message,
    MessageBox,
    Notification
} from 'element-ui';
import hostUrl from './baseUrl.js'
// const hostUrl = 'https://cloud.supply.sxruanjian.cn/admin';
// 创建axios实例
const service = axios.create({
    withCredentials: true,
    baseURL: hostUrl, // api的base_url
    timeout: 5000 // 请求超时时间
});
// 请求拦截器
service.interceptors.request.use(
    config => {
        const accessToken = localStorage.getItem('Supply-Access-Token') ? localStorage.getItem('Supply-Access-Token') : '';
        const getSign = (signJson, key) => {
            var keys = [];
            for (let k in signJson) {
                keys.push(k);
            }
            keys.sort();
            var kv = [];
            for (let k in keys) {
                kv.push(keys[k] + '=' + signJson[keys[k]]);
            }
            var sign = kv.join('&');
            sign = sign + '&key=' + key;
            sign = md5(sign);
            return sign;
        }
        //得到参数对象
        const getParam = () => {
            let appId = "09d32854b7a9de58";
            let appKey = "5668da1409d32854b7a9de588c8b526c";
            let timestamp = parseInt((new Date()).getTime() / 1000);
            let nonce = Math.floor(Math.random() * 8999) + 1000;
            if (config.data == undefined || config.data == {}) {
                config.data = {}
            }
            config.data.appid = appId
            config.data.nonce = nonce
            config.data.timestamp = timestamp
            let signs = '';
            if(config.data.sign){
                delete config.data.sign
                signs = getSign(config.data, appKey)
            }else{
                signs = getSign(config.data, appKey)
            }
            config.data.sign = signs;
            return config.data;
        }
        const paramVal = getParam();
        config.headers['Authorization'] = accessToken;
        config.headers['X-CSRF-TOKEN'] = localStorage.getItem('X-Csrf-Token') ? localStorage.getItem('X-Csrf-Token') : '';
        if (config.method == 'get') {
            config.params = { ...paramVal, ...config.params }
        } else {
            config.data = { ...config.data, ...paramVal }
        }
        return config;
    },
    error => {
        // 请求错误处理
        console.log(error); // for debug
        Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    response => {
        // 对响应数据做处理，例如只返回data部分
        const res = response.data;
        if (localStorage.getItem('X-Csrf-Token')) {
            localStorage.setItem("X-Csrf-Token", '');
        }
        if (res.code != 0) {
            if (res.code == 101) { //token失效
                // localStorage.clear();
                localStorage.removeItem('Supply-Access-Token');
                location.reload();
            } else {
                Message({
                    message: res.msg,
                    type: 'error'
                })
            }
        }
        return response.data;
    },
    error => {
        Message({
            message: '网络不给力,请稍后重试',
            type: 'error',
            duration: 5 * 1000
        });
        return Promise.reject(error);
    }
);

export default service;